//
//  HomeSearchHotKeywordView.swift
//  iFishApp
//
//  Created by Bob on 2022/3/4.
//

import SwiftUI

struct HomeSearchHotKeywordView: View {
    // 一个定时器，每三秒触发一次
    private let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
    
    private let ITEM_HEIGHT: CGFloat = 40
    
    @State private var currentIndex: Int = 1
    
    private let hotKeywords: [String] = ["春风120","MacBook Pro","iPhonne 13 Pro","华为Mate P50","红米K40","绿水鬼", "iPad 5 Pro"]
    
    // 无缝轮播
    private var loopHotKeywords: [String] {
        return [hotKeywords.last!] + hotKeywords + [hotKeywords.first!]
    }
    
    var body: some View {
        
        let currentOffsetY = CGFloat(currentIndex) * ITEM_HEIGHT
        
        GeometryReader { proxy in
            VStack(alignment: .leading, spacing: 0) {
                ForEach(hotKeywords, id: \.self) { keyword in
                    Text(keyword)
                        .foregroundColor(.black.opacity(0.5))
                        .font(.system(size: 14, weight: .bold))
                        .frame(maxWidth: .infinity)
                        .frame(height: ITEM_HEIGHT)
                }
            }
            .frame(height: ITEM_HEIGHT, alignment: .top)
            .offset(x: 0, y: -currentOffsetY)
            .clipped()
            // 定时器执行
            .onReceive(timer) { _ in
                // 添加一个动画效果
                withAnimation(.spring()) {
                    // 实现热词滚动, 计算当前要显示的热词的index，然后利用index 计算出y轴偏移量
                    if currentIndex == loopHotKeywords.count - 1 {
                        currentIndex = 0
                    } else {
                        currentIndex += 1
                    }
                }
            }
            // 监听currenntIndex的变化
            .onChange(of: currentIndex) { newValue in
                if newValue == 0 {
                    currentIndex = loopHotKeywords.count - 2
                } else if newValue == loopHotKeywords.count - 1 {
                    currentIndex = 1
                }
        }
        }
    }
}

struct HomeSearchHotKeywordView_Previews: PreviewProvider {
    static var previews: some View {
        HomeSearchHotKeywordView()
    }
}
